const express = require('express')
const conn = require('../mysql.js')
const stuRouter = express.Router()
const jwt = require("jsonwebtoken")
const multer = require('multer')
const fs = require('fs')
const upload = multer({ dest: 'uploads/' })
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;
const { sendMail } = require('node-send-email')
const nodemailer = require('nodemailer')



// 用户模块
// 获取列表
stuRouter.get('/login', (req, res) => {
  const stuId = req.query.stuId
  const password = req.query.password

  const sql = `SELECT *FROM stu_user WHERE stuId = ?;`;
  conn.query(sql, [Number(stuId)], (err, result, fields) => {
    const user = result[0];
    if (err) {
      return console.log('==err', err)
    }
    if (!user) {
      return res.send({
        code: 401,
        data: {},
        msg: '无该用户,请注册'
      })
    }
    if (user.password != password) {
      return res.send({
        code: 401,
        data: {},
        msg: '密码错误,请重新输入'
      })
    }
    const { id, stuId } = user;
    const token = jwt.sign({ id, stuId }, "123", {
      expiresIn: 60 * 60 * 24,
      // algorithm: 'RS256'
    });
    return res.send({
      code: 200,
      data: {
        id,
        stuId,
        token,
      },
      msg: '登录成功'
    })

  })
})
stuRouter.post('/regiser', (req, res) => {
  let stuId = req.body.stuId
  let password = req.body.password
  let email = req.body.email
  let yanzhen = req.body.yanzhen

  // 判断这次注册的用户有没有被注册
  const sqlOne = `SELECT *FROM stu_user WHERE stuId = ?;`;
  conn.query(sqlOne, [stuId], (err, result, fields) => {
    if (err) {
      return console.log('==err', err)
    }
    if (result.length > 0) {
      return res.send({
        code: 200,
        data: {},
        msg: '该名称已被注册'
      })
    }
    const sqlTwo = `SELECT *FROM yanzhen WHERE yanzhengNum = ?;`;
    conn.query(sqlTwo, [yanzhen], (err, result, fields) => {
      const data = result[0];
      if (!data) {
        return res.send({
          code: 401,
          data: {},
          msg: '验证码错误'
        })
      }
      // 创建用户
      const sqlThree = 'insert into stu_user (stuId, password, email) values(?, ?, ?)'
      conn.query(sqlThree, [stuId, password, email], (err, result, fields) => {
        if (err) {
          return console.log('==err', err)
        }
        res.send({
          code: 200,
          data: {},
          msg: '注册成功'
        })
      }
      )
    })
  })
})
// 编辑用户管理
stuRouter.post('/updateUserData', (req, res) => {
  let id = req.body.id
  let username = req.body.username
  let identity = req.body.identity
  let state = req.body.state
  let identityId = req.body.identityId
  let sql =
    'update users set username=?,identity=?,state=?,identityId=? where id=?'
  conn.query(
    sql,
    [username, identity, state, Number(identityId), Number(id)],
    (err, result) => {
      if (err) {
        return console.log('==err', err)
      }
      console.log(result)
      res.send(result)
    }
  )
})
stuRouter.post('/getUser', (req, res) => {
  const stuId = req.body.stuId
  const sql = `SELECT * FROM stu_user where stuId = ?`;
  conn.query(sql, [Number(stuId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/getBillList', (req, res) => {
  const stuId = req.body.stuId
  const sql = `SELECT * FROM orderdb where stuId = ?`;
  conn.query(sql, [Number(stuId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/changeMy', (req, res) => {
  const { stuId, name, message } = req.body
  const sql = `update stu_user set name=?, message=? where stuId=?`;
  conn.query(sql, [name, message, Number(stuId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '修改成功'
    })

  })
})

// 首页
stuRouter.get('/homeList', (req, res) => {
  const sql = `SELECT * FROM admin_user`;

  conn.query(sql, (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/getdoor', (req, res) => {
  const poiId = req.body.poiId

  const sql = `SELECT * FROM admin_user where poiId = ? `;

  conn.query(sql, [Number(poiId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/getfood', (req, res) => {
  const poiId = req.body.poiId

  const sql = `SELECT * FROM admin_food where poiId = ?`;

  conn.query(sql, [Number(poiId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/getdoorV2', (req, res) => {
  const type = req.body.type

  const sql = `SELECT * FROM admin_user where type = ?`;

  conn.query(sql, [type], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/buyOrder', (req, res) => {
  const timesTamp = Date.now()
  const time = parseInt(timesTamp.toString().slice(-4))

  const {
    name,
    price,
    type,
    overMessage,
    stuId,
    poiId,
    foodId,
    orderCome,
    isSuccess,
    doorName,
    nowNum
  } = req.body
  const sql = `SELECT * FROM orderdb where isSuccess = ? and stuId = ?`
  conn.query(sql, [isSuccess, stuId], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    if (data.length > 0) {
      return res.send({
        code: 401,
        data,
        msg: '您已有订单尚未完成，请完成后再重新点餐'
      })
    } else {
      const sqlV2 = 'INSERT INTO orderdb (name, price, type, overMessage, stuId, poiId, foodId, orderCome, isSuccess, doorName, orderId, nowNum) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
      conn.query(sqlV2, [name, price, type, overMessage, stuId, poiId, foodId, orderCome, isSuccess, doorName, Number(foodId + time), nowNum], (err, result, fields) => {
        const data = result
        if (err) {
          return console.log('==err', err)
        }
        return res.send({
          code: 200,
          data,
          msg: '购买成功'
        })

      })
    }

  })

})

// 搜索
stuRouter.post('/homeSearch', (req, res) => {
  const { doorName } = req.body
  const sql = `SELECT * FROM admin_user where door_name like ?`;

  conn.query(sql, [`%${doorName}%`], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})



// 订单
stuRouter.post('/orderList', (req, res) => {
  const stuId = req.body.stuId
  const isSuccess = req.body.isSuccess

  let sql = `SELECT * FROM orderdb where isSuccess = ? and stuId = ?`;
  conn.query(sql, [isSuccess, Number(stuId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      total: result.length,
      msg: '查询成功'
    })
  })

})

// 盲盒
stuRouter.get('/cateList', (req, res) => {
  const sql = `SELECT * FROM box`;

  conn.query(sql, (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/getcateList', (req, res) => {
  const foodId = req.body.foodId

  const sql = `SELECT * FROM box where foodId = ?`;

  conn.query(sql, [Number(foodId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})
stuRouter.post('/getFoodList', (req, res) => {
  const foodId = req.body.foodId

  const sql = `SELECT * FROM message where foodId = ?`;

  conn.query(sql, [Number(foodId)], (err, result, fields) => {
    const data = result
    if (err) {
      return console.log('==err', err)
    }
    return res.send({
      code: 200,
      data,
      msg: '查询成功'
    })

  })
})



// 上传商户门店图片
stuRouter.post('/stu_upload', upload.array('stuFiles', 9), (req, res) => {
  const { stuId } = req.body
  if (req.files) {
    req.files.forEach(file => {
      const url = fs.readFileSync(file.path, { encoding: 'base64' })
      const sql = 'INSERT INTO stu_images (stuId, url) VALUES (?, ?)'
      conn.query(sql, [stuId, url], (err, result) => {
        if (err) throw err;
      })
    })
    return res.send(
      {
        code: 200,
        msg: '上传成功'
      }
    )
  } else {
    return res.send(
      {
        code: 200,
        msg: '上传失败'
      }
    )
  }
})

stuRouter.get('/stu_images', (req, res) => {
  let sql = 'SELECT * FROM stu_images';
  const { stuId } = req.query
  if (stuId) {
    sql += `WHERE stuId = ${stuId} `
  }
  conn.query(sql, (err, result) => {
    if (err) throw err;
    return res.send({
      code: 200,
      data: result,
      msg: '查看成功'
    })
  })
})


// 支付宝
const alipaySdk = new AlipaySdk({
  appId: '9021000136662584',
  privateKey: 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCO5dg6NKEJ0MlwkhGSz1vSci3IOXpgb8/xFtH6/TsbZ/PkwBUIz4H6ThCqWcZGrQM2+Kuj86I9w8FtfApc59vuYdr7ih34H2KfSEdaV2IiRtBgGjVevKbeNBSdFBk0Iek/VctjSV9+zefaAptr25L+A6HW9PEVqVwpyKNhIQ1d/1/G7TOyLjcXX+ZWIdmePva+cgjhG0wsvLZU8VjVzpSfmqpN+Jgi4FOR0y8uuuQzf6mpIHevoenfgAaoNNSfC1N97IonGtb6mc6QEip0ZKSY2CN971I0cxvnkMDnHwmUkHGQX110CsUgxZP1wqFnnULGJZgEnwrTrcLVYig0m23xAgMBAAECggEAIX5MFTB6wnM2k/UYu2Fw8z2h73lRbsMmaSrhIsQyE3VlHCvNglgo7gNYMqWCLNSmmT7l9DLJx1JXxxK41xfdW92B102DQsIQeqcVWl56+O/CLZRXCBKNxi1M25h3Y9nC8v5oAqiTAoS+oEHWLgy0QmeVim21CE++82g8qyp1GJ/Ffy0y+zsWjcGsKxzmqJdunOv31tnTcneQ9PoJQfCGWaIScQ1ltmBWEjUQExkkHXTO2dfmalJIFfwNXBIgc32qCWsJdEcDMf0ieVcPRCbYAxckGH1jrs4q/jEiImUNOzL8+aZh3oiwPJbJKUGew0noxs8ncfmPUadFS7AlD5mw8QKBgQDX/m7IHJ581DLyDhzoIScTQqLIIOaGFUhReRZmIo7IEA/P3tpwmNaR6nbXXBY1rHVLKMEK6uHBx+IREU3ipp5krtNByeIgUu3XvygMd2rex/siCysp4G6W1yU2FiKIE1XP8VP0N7tE8s2AhKLTaxgfRSQ5Ei1whfzm7sQLIjab5QKBgQCpXX07/y/N2Nhteh1phcqOkQxrau8XDFJjndN6W8IvjTgGKZd3lnhGb6D3nBfe5dGmq1L4r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i-sandbox.dl.alipaydev.com/gateway.do',
  signType: 'RSA2',
});

stuRouter.post('/create-payment', async (req, res) => {
  const { totalAmount, subject } = req.body;
  const formData = new AlipayFormData();
  formData.setMethod('get');
  formData.addField('returnUrl', 'http://localhost:3000/home');
  formData.addField('bizContent', {
    outTradeNo: Date.now().toString(), // 订单号
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount, // 订单金额
    subject, // 订单标题
  });

  try {
    const result = await alipaySdk.exec(
      'alipay.trade.page.pay',
      {},
      { formData: formData }
    );
    res.json({ url: result });
  } catch (error) {
    res.status(500).send(error.toString());
  }
});

// qq邮箱验证
const transporter = nodemailer.createTransport({
  service: 'qq',
  auth: {
    user: '1191928508@qq.com',
    pass: 'azjxewgcyrdejgch' // 注意：这里是授权码，不是邮箱密码，需要在QQ邮箱设置中获取
  }
});

stuRouter.post('/send-email', (req, res) => {
  const { email } = req.body;
  const code = Math.floor(100000 + Math.random() * 900000); // 生成六位随机验证码

  let sql = `update yanzhen set yanzhengNum = ? where id = 1`;
  conn.query(sql, [code], (err, result) => {
    if (err) {
      return console.log('==err', err)
    }
    res.send(result)
  }
  )

  const mailOptions = {
    from: '1191928508@qq.com',
    to: email,
    subject: '验证码',
    text: `您的验证码是：${code}`
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).send(error.toString());
    }
    res.status(200).send('验证码已发送');
  });
});




//导出
module.exports = stuRouter
